import axios from "axios"
import { ElMessage } from "element-plus"
import { PiniaPluginContext } from "pinia"
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import * as PIXI from 'pixi.js'
import { TextAttr } from "./Constant"

type Options = {
    key?: string
}
const baseWidth = 1661;
const baseHeight = 827;

export function renderText(props: TextAttr) {
    let text = new PIXI.Text(props.text, {
        fontFamily: props.fontFamily || "楷体",
        fill: props.color || '#000',
        fontSize: (props.fontSize || 20) * (props.scaleSize || 1),
        align: "center",
    }) as PIXI.Text;
    text.position.set(props.posX || 0, props.posY || 0)
    props.container.addChild(text)
    return text
}

export function getScaleSize() {
    let scaleX = window.innerWidth / baseWidth
    let scaleY = window.innerHeight / baseHeight
    return Math.min(scaleX, scaleY)
}

export function getEncryptionInfo(type: string, info: string) {
    let res = info
    if (type == 'email') {
        let arr = info.split('@')
        res = arr[0].slice(0, 3) + '****' + arr[1]
    }
    return res
}

export function getUserInfo() {
    const User = useUserStore()
    let { user } = storeToRefs(User);
    return JSON.parse(JSON.stringify(user.value));
}

export async function loadRemoteResource(url: string) {
    url = Util.getImgUrl(url)
    let cache = PIXI.utils.TextureCache[url]
    if (!cache) {
        PIXI.Assets.add(url, url)
    }
    await PIXI.Assets.load(url)
    return PIXI.utils.TextureCache[url]
}

export let usernameValidate = [{
    required: true,
    message: '用户名不能为空！',
    trigger: 'submit'
},
{ min: 3, max: 18, message: '用户名长度为3-18位', trigger: 'blur' },
{ pattern: /^[a-zA-z][\d\w]/, message: '用户名为数字或字母，且必须以字母开头', trigger: 'blur' }
]
export let passwordValidate = [{
    required: true,
    message: '密码不能为空！',
    trigger: 'submit'
},
{ min: 5, max: 18, message: '密码长度为5-18位', trigger: 'blur' }
]
export let emailValidate = [
    {
        required: true,
        message: '邮箱不能为空',
        trigger: 'blur'
    },
    {
        required: true,
        type: 'email',
        message: '错误的邮箱格式',
        trigger: 'blur'
    }
]
export class Util {
    static __piniaKey = '__PINIAKEY__'
    static host = 'http://115.120.233.224'
    // static host = 'http://localhost'
    static setLocalStorage(key: string, value: any) {
        localStorage.setItem(key, JSON.stringify(value))
    }
    static getLocalStorage(key: string) {
        return localStorage.getItem(key) || '{}'
    }
    static getImgUrl(url: string) {
        return `${this.host}/${url}`
    }
    static async routerBeforeHook(to: any, from: any, next: any) {
        if (!to.meta?.notNeedCheckToken) {
            const token = localStorage.getItem('token')
            if (!token) {// 没有token
                ElMessage({
                    message: '没有token令牌!',
                    type: 'error',
                })
                return next({ path: '/login' })
            }
            const { data } = await axios.get('/user', {
                headers: { token }
            })
            if (data.code !== '0000') { // token无效
                ElMessage({
                    message: '无效token!',
                    type: 'error',
                })
                next({ path: '/login' })
            }
        }
        next()
    }
    static piniaPlugin(options: Options) {
        return (content: PiniaPluginContext) => {
            let data = JSON.parse(this.getLocalStorage(`${options.key ?? this.__piniaKey}`))
            let { store } = content
            store.$subscribe(() => {
                this.setLocalStorage(`${options.key ?? this.__piniaKey}`, store.$state)
            })
            return {
                ...data
            }
        }
    }
    static getVerificationCode = (length: number = 6) => {
        let verificationCode = ''
        function getRandom() {
            return Math.floor(Math.random() * 10)
        }
        for (let i = 0; i < length; i++) {
            verificationCode = verificationCode + getRandom()
        }
        return verificationCode
    }
    static randomInt(num: number) { // 返回 [ 0, num) 之间的随机整数
        return Math.floor(Math.random() * num)
    }

    static deepClone<T>(obj: T, hash = new WeakMap()): T {
        if (typeof obj !== 'object' || obj == null) {
            return obj
        }
        if (hash.has(obj)) { return hash.get(obj) }; // 解决相互引用问题

        let res: any = Array.isArray(obj) ? [] : {}

        hash.set(obj, res)

        let symbolKeys = Object.getOwnPropertySymbols(obj)
        symbolKeys.forEach((key) => {
            res[key] = obj[key] !== 'object' ? obj[key] : this.deepClone(obj[key]);
        })

        for (let key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                res[key as string] = typeof obj[key] !== 'object' ? obj[key] : this.deepClone(obj[key]);
            }
        }
        return res
    }
}

